var mTitle        = document.title;
var start_time    = new Date();
var countTimeout  = null;

function startCounter( obj_id, eventTime, update, funct )
{
	start_time	= new Date();
	countTime( obj_id, eventTime, update, null, funct );
}

function countTime( obj_id, left_time, updateTitle, divElement, funct )
{
	if ( updateTitle == undefined ) updateTitle	= true;

	var obj   = document.getElementById( obj_id );
	var now   = new Date();
	var left  = left_time - Math.round( ( now.getTime() - start_time.getTime() ) / 1000.0 );

	if ( left < 0 ) 
  {  
    obj.innerHTML	= '';

		var addr = document.location.toString();
    
		if ( addr.indexOf('?') == -1 ) addr += '?';

		addr += '&r2=' + Math.floor( Math.random() * 1000 );

		if ( !( funct != undefined || funct != '' ) )
    {
      window.setTimeout( funct + "('" + obj_id + "')", 100 );
		}
    else if ( !( divElement != undefined || divElement != '' ) )
    {
      doDivLoad( addr, divElement );
		}
    else if ( updateTitle == 1 ) setTimeout( "document.location='" + addr + "'", 1000 );

		return;
  }

	var days = hour = min = 0;
  
	if ( left > 59 )
  {
    min   =	Math.floor( left / 60 );
    left  =	left % 60;
	}
  
	if ( min > 59 )
  {
		hour  =	Math.floor( min / 60 );
		min   =	min % 60;
	}
  
	if ( hour > 23 )
  {
		days  =	Math.floor( hour / 24 );
		hour  =	hour % 24;
	}  

  days_n  = get_number( days, 'день', 'дня', 'дней' );
  hour_n  = get_number( hour, 'час', 'часа', 'часов' );
  min_n   = get_number( min, 'минута', 'минуты', 'минут' );
  left_n  = get_number( left, 'секунда', 'секунды', 'секунд' );
  
  var stamp = '';
  
  if ( days ) stamp += days + days_n + ' ';
  if ( hour ) stamp += hour + hour_n + ' ';
  if ( min  ) stamp += min + min_n + ' ';
  
  stamp += left + left_n;
  
	obj.innerHTML	= 'До начала фестиваля<br />' + stamp;

  if ( updateTitle ) document.title = '[' + stamp + ']';
  
	countTimeout = window.setTimeout( "countTime('" + obj_id + "'," + left_time + "," + updateTitle + ",'" + divElement + "','" + funct + "');", 1000 );
}

function doDivLoad( url, divElement )
{
	$("#"+divElement).load( url );
}

function get_number( num, w1, w2, w3 )
{
    num = num + '';

    var last_char = num.charAt(num.length - 1);

    var w_res = w3;

    if (num >= 11 && num <= 14) {

        w_res = w3;

    } else if (last_char == 1) {

        w_res = w1;

    } else if (last_char >= 2 && last_char <= 4) {

        w_res = w2;

    }

    return ' ' + w_res;
}